package csu.web.mypetstore.web.servlet;

import csu.web.mypetstore.domain.Account;
import csu.web.mypetstore.domain.Cart;
import csu.web.mypetstore.domain.Product;
import csu.web.mypetstore.persistence.AccountDao;
import csu.web.mypetstore.service.AccountService;
import csu.web.mypetstore.service.CartService;
import csu.web.mypetstore.service.CatalogService;
import csu.web.mypetstore.service.LogService;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

public class SignOnServlet extends HttpServlet {
    private static final String SIGNON_FORM = "/WEB-INF/jsp/account/signon.jsp";
    private String username;
    private String password;
    private String msg;
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {


        this.username = req.getParameter("username");
        this.password = req.getParameter("password");

        //检查是否正确
        if(!validate())
        {
            req.setAttribute("signOnMsg",this.msg);
            req.getRequestDispatcher(SIGNON_FORM).forward(req,resp);
        }else {
            AccountService accountService = new AccountService();
            Account loginAccount = accountService.getAccount(username,password);
            if(loginAccount==null)
            {
                this.msg = "Username Or Password Error!";
                req.getRequestDispatcher(SIGNON_FORM).forward(req,resp);
            }else
            {
                HttpSession session = req.getSession();
                session.setAttribute("loginAccount",loginAccount);

                //从数据库中调取购物车信息
                CartService cartService = new CartService();
                Cart cart = cartService.getCart(loginAccount.getUsername());
                if(cart!=null){
                    session.setAttribute("cart",cart);
                }

                if(loginAccount.isListOption()){
                    CatalogService catalogService = new CatalogService();
                    List<Product> myList = catalogService.getProductListByCategory(loginAccount.getFavouriteCategoryId());
                    session.setAttribute("myList",myList);
                }

                resp.sendRedirect("MainForm");
            }
        }
    }

    private boolean validate(){
        if(this.username == null|| this.username.equals("")){
            this.msg = "Username is empty!";
            return false;
        }
        if(this.password == null|| this.password.equals("")){
            this.msg = "Password is empty!";
            return false;
        }
        return true;
    }
}
